#!/usr/bin/env bash
set -euo pipefail
file="${1:-access.log}"
awk 'BEGIN{FS="\""}{split($1,a," ");ip=a[1];split($2,b," ");uri=b[2];split($3,c," ");status=c[1];ua=$6;if(status ~ /^4[0-9][0-9]$/){four[ip]++} if(uri!=""){key=ip SUBSEP uri;u[key]=1} if(ua!=""){lastua[ip]=ua}}END{for(ip in four){count=0;for(k in u){split(k,t,SUBSEP);if(t[1]==ip){count++}}print ip,four[ip],count,lastua[ip]}}' "$file" | sort -k2,2nr | head -5
